import importlib
import os
import sys

def mdk6AddSrcGroup(parent, name, source, abspath_prj):
    group_yml = {
        'group': name,
        'files': []
    }

    for src in source:
        path = str(src)
        path = os.path.relpath(path, abspath_prj)

        files_file = {
            'file': path
        }
        group_yml['files'].append(files_file)

    # skip empty group
    if group_yml['files']:
        parent.append(group_yml)

def mdk6AddPath(parent, paths, abspath_prj):
    if paths == None:
        return

    for path in paths:
        path = os.path.relpath(path, abspath_prj)

        parent['add-path'].append(path)

def MDK6Project(target, script):
    abspath_prj = os.path.dirname(os.path.abspath(target))

    try:
        yaml = importlib.import_module('yaml')
    except ImportError:
        print("Please install PyYAML: pip install pyyaml")
        return False

    cprj_file = None
    try:
        cprj_file = open('project.cproject.yml', encoding='utf-8')
    except FileNotFoundError:
        print("project.cproject.yml not found")
        print("Please use 'Arm CMSIS Solution' to generate it first")
        return False
    except Exception as e:
        print("open project.cproject.yml fail")
        return False

    try:
        data = yaml.safe_load(cprj_file)
    except yaml.YAMLError as e:
        print("Error parsing YAML file")
        if cprj_file:
            cprj_file.close()
        return False
    finally:
        if cprj_file:
            cprj_file.close()

    if 'project' not in data:
        print("Can't find 'project' node")
        return False
    if 'groups' not in data['project']:
        print("Can't find 'groups' node")
        return False
    if 'setups' not in data['project']:
        print("Can't find 'setups' node")
        return False

    setups = data['project']['setups']
    if len(setups) < 1:
        print("'setups' node is empty")
        return False

    setups[0]['add-path'] = []

    for group in script:
        if 'CPPPATH' in group:
            mdk6AddPath(setups[0], group['CPPPATH'], abspath_prj)

    data['project']['setups'] = setups

    try:
        data['project']['groups'] = []

        for group in script:
            mdk6AddSrcGroup(data['project']['groups'], group['name'], group['src'], abspath_prj)

    except Exception as e:
        print("Error processing groups")
        return False

    cprj_file = open('project.cproject.yml', 'w', encoding='utf-8')
    cprj_file.truncate()
    yaml.dump(data, cprj_file, default_flow_style=False, allow_unicode=True, sort_keys=False)
    cprj_file.close()

    return True
